import React, { useState } from 'react';
import './WrjFront.less'
import {useDispatch,useSelector} from "react-redux"
import {addFrontImg} from "../../../store/model/counter"

const Front: React.FC = () => {

    const dispatch=useDispatch()
    const [imageUrl,setImgageUrl]=useState('')
    const [frontImg,setFrontImg]=useState('')

    const handleFileChange=(event:any)=>{
        const file = event.target.files[0];
        if (file) {
            const reader: FileReader = new FileReader();
            reader.onload =  () => {
                const img:HTMLImageElement = new Image();
                if(typeof reader.result==='string'){
                    img.src = reader.result;
                }
                img.onload =  () => {
                    const maxWidth = 300; // 设置最大宽度
                    const maxHeight = 300; // 设置最大高度
                    const imageWidth = img.width;
                    const imageHeight = img.height;
                    
                    // 计算新的宽度和高度，以保持纵横比
                    let newWidth=0 
                    let newHeight=0
                    if (imageWidth > imageHeight) {
                        newWidth = maxWidth;
                        newHeight = (imageHeight / imageWidth) * maxWidth;
                    } else {
                        newHeight = maxHeight;
                        newWidth = (imageWidth / imageHeight) * maxHeight;
                    }
                    const canvas: HTMLCanvasElement = document.createElement('canvas');
                    const ctx: CanvasRenderingContext2D | null = canvas.getContext('2d');
                    canvas.width = newWidth;
                    canvas.height = newHeight;
                    ctx!.drawImage(img, 0, 0, newWidth, newHeight);
                    
                    // 将压缩后的图片转换为Base64数据URL
                    const imgurl = canvas.toDataURL('image/jpeg', 0.2); // 可以调整压缩质量
                    setImgageUrl(imgurl)
                    setFrontImg(imgurl.split(',')[1])
                    // dispatch(addFrontImg(imgurl.split(',')[1]))
                    dispatch(addFrontImg(imgurl))
                };
            }
            reader.readAsDataURL(file);
        }
    }
    
    return (
        <div className="wrj-front-file-input">
            {
                imageUrl==''?
                <input type="file" onChange={handleFileChange}/>:
                <img src={imageUrl} className="wrj-frontImg" />
            }
        </div>
    );
};

export default Front;